#!/usr/bin/env python
"""
CTPRPCDebug

debugging utilities used by CTP-RPC v2 protocol
"""

import os, sys
import thread
from datetime import datetime


# public varaibles
level = 0
output_stream = sys.stderr


#private members
_write_lock = thread.allocate_lock()


#public methods
def write ( lvl, msg ):
	if ( level < lvl ): return
	_write_lock.acquire()
	output_stream.write ( "#DEBUG%d# %s\n" % ( lvl, msg ) )
	output_stream.flush()
	_write_lock.release()


def error ( msg ):
	if ( level < 1 ): return
	_write_lock.acquire()
	output_stream.write ( "#ERROR# %s\n" % msg )
	output_stream.flush()
	_write_lock.release()


def tohex ( s ):
	ret = ""
	if isinstance ( s, long ):
		s = hex ( s ) [ 2 : -1 ]
		l = len ( s )
		for i, p in enumerate ( xrange ( 0, l, 2 ) ):
			if i % 16 == 0: ret += "\n        "
			ret += s [ p : p + 2 ] + " "
	else:
		for i, c in enumerate ( s ):
			if i % 16 == 0: ret += "\n        "
			ret += "%02X " % ord ( c )
	return ret

